package com.example.administrator.myapplication.mode;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.base.BaseActivity;
import com.example.administrator.myapplication.utils.Global;
import com.example.administrator.myapplication.utils.LiteOrmUtil;
import com.litesuits.orm.db.annotation.Column;
import com.litesuits.orm.db.annotation.Ignore;
import com.litesuits.orm.db.annotation.PrimaryKey;
import com.litesuits.orm.db.annotation.Table;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.enums.AssignType;

import java.util.ArrayList;

import static com.example.administrator.myapplication.utils.LiteOrmUtil.getLiteOrm;


/**
 * 说明：用户对象类
 * 作者： 阳2012; 创建于： 2017/5/6 8:38
 */
@Table("UserData")
public class UserInfo {
    //用户对象
    @Ignore
    public static UserInfo userData;
    @PrimaryKey(AssignType.AUTO_INCREMENT)
    private int id;
    @Column("isLogin")
    private boolean isLogin = false;
    @Column("account")
    private String account;
    @Column("password")
    private String password;

    public UserInfo() {
    }

    public UserInfo(String account, String password) {
        this.account = account;
        this.password = password;
    }

    public static UserInfo getInstance() {
        try {
            userData = (getLiteOrm().query(UserInfo.class)).size() > 0 ? (getLiteOrm().query(UserInfo.class)).get(0) : new UserInfo();
            if ((getLiteOrm().query(UserInfo.class)).size() == 0) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userData;
    }


    /**
     * 退出登录
     * <p>
     * <p>
     * int res = LiteOrmUtil.getLiteOrm().update(WhereBuilder.create(UserInfo.class).where("isLogin=?", true), new ColumnsValue(new String[]{"isLogin"}, new Boolean[]{false}), ConflictAlgorithm.None);
     */
    private static boolean exit(Context context) {
        //清除所有用户
        int res = getLiteOrm().deleteAll(UserInfo.class);
        // 跳转到登录页面
//        ActivityManager.getInstance().exitAllActivity();
        return true;
    }

    /**
     * 退出登录,对话框
     */
    public static void exitLogin(final Activity context) {
        MaterialDialog materialDialog = new MaterialDialog.Builder(context)
                .title("提示")
                .positiveText("确定")
                .negativeColorRes(R.color.gray)
                .negativeText("取消")
                .content("确定退出登录吗？")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        exit(context);
                    }
                })
                .build();
        materialDialog.show();

    }


    /**
     * 保存数据到数据库（）
     *
     * @param data 被保存的数据，这个数据会被默认成数据库的唯一登录数据
     * @return
     */
    public static boolean save(UserInfo data, BaseActivity activity) {
        if (data != null) {
            try {
                long count = LiteOrmUtil.getLiteOrm().queryCount(QueryBuilder.create(UserInfo.class).where("account=?", data.account));
                if (count == 0) {
                    userData = data;
                    getLiteOrm().save(data);
                    activity.sendBroadcast(new Intent(Global.REGIST_SUCCEED));
                    return true;
                } else {
                    activity.showWarningMessage("该帐户已经注册过了");
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;

        }

    }


    public static boolean checkLogin(UserInfo data, BaseActivity activity) {
        try {
            ArrayList<UserInfo> da = LiteOrmUtil.getLiteOrm().query(QueryBuilder.create(UserInfo.class).where("account=?", data.account).whereAnd("password=?", data.password));
            if (da.size() > 0) {
                userData = da.get(0);

                activity.sendBroadcast(new Intent(Global.LOGIN_SUCCEED));
                return true;
            } else {
                long count = LiteOrmUtil.getLiteOrm().queryCount(QueryBuilder.create(UserInfo.class).where("account=?", data.account));
                if (count == 0) {
                    activity.showWarningMessage("该帐户没有注册");
                } else {
                    activity.showWarningMessage("该帐或密码不对");
                }
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //                                                 阳_2017/3/4:以下以基本方法
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public static UserInfo getUserData() {
        return userData;
    }

    public int getId() {
        return id;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public String getAccount() {
        return account;
    }

    public String getPassword() {
        return password;
    }
}
